import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE || '/api',
  timeout: 8000
})

instance.interceptors.request.use(cfg => {
  const { token } = useAuthStore()
  if (token) cfg.headers.Authorization = `Bearer ${token}`

  // 确保GET请求没有Content-Type头
  if (cfg.method.toLowerCase() === 'get') {
    delete cfg.headers['Content-Type']
  } else {
    // 对于其他请求方法，设置JSON内容类型（除了blob请求）
    if (cfg.responseType !== 'blob') {
      cfg.headers['Content-Type'] = 'application/json'
      if (cfg.data && typeof cfg.data === 'object') {
        cfg.data = JSON.stringify(cfg.data)
      }
    }
  }

  // 添加Accept头（对于blob请求使用不同的Accept）
  if (cfg.responseType === 'blob') {
    cfg.headers['Accept'] = 'application/octet-stream'
  } else {
    cfg.headers['Accept'] = 'application/json'
  }

  return cfg
})

instance.interceptors.response.use(
  res => {
    // 如果是blob响应，直接返回blob数据
    if (res.config.responseType === 'blob') {
      return res.data
    }
    return res.data
  },
  err => {
    if (err.response?.status === 401) {
      useAuthStore().logout()
      return Promise.reject('登录已过期')
    }
    ElMessage.error(err.response?.data?.msg || '请求异常')
    return Promise.reject(err)
  }
)

export function downloadFile(response, fileName) {
  const blob = new Blob([response.data])
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(link.href)
}

export const request = (method, url, data = null, params = null, config = {}) => {
  return instance({
    method: method.toLowerCase(),
    url: url,
    data: data,
    params: params,
    ...config
  })
}

export default instance